package com.macro.mall.tiny.modules.oms.controller;


import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.macro.mall.tiny.common.api.CommonResult;
import com.macro.mall.tiny.modules.oms.model.OmsSettleApply;
import com.macro.mall.tiny.modules.oms.service.OmsSettleApplyService;
import com.macro.mall.tiny.modules.ums.model.UmsAdmin;
import com.macro.mall.tiny.modules.ums.model.UmsMember;
import com.macro.mall.tiny.modules.ums.service.UmsAdminService;
import com.macro.mall.tiny.modules.ums.service.UmsMemberService;
import com.macro.mall.tiny.security.util.JwtTokenUtil;
import com.macro.mall.tiny.security.util.MemberContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 提现申请表 前端控制器
 * </p>
 *
 * @author tyrone
 * @since 2024-10-31
 */
@RestController
@RequestMapping("/oms/omsSettle")
@Api(tags = "OmsSettleApplyController")
@Tag(name = "OmsSettleApplyController", description = "提现管理")
public class OmsSettleApplyController {

    @Autowired
    private OmsSettleApplyService omsSettleApplyService;


    @Autowired
    private UmsMemberService umsMemberService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UmsAdminService umsAdminService;

    private static final Snowflake snowflake = IdUtil.getSnowflake(2, 1);


    @ApiOperation("发起提现申请 只需要给openId fee即可")
    @PostMapping("applySettle")
    public CommonResult<OmsSettleApply> applySettle(@RequestBody OmsSettleApply apply) {
        UmsMember member = MemberContext.getMember();

        if (apply.getOpenId() == null || apply.getFee() == null || !member.getOpenId().equals(apply.getOpenId())) {
            return CommonResult.failed("参数错误");
        }
        if (apply.getFee() < 100 || apply.getFee() > 30000 ) {
            return CommonResult.failed("提现额度超过限制，单笔提现金额需在1-300元之间");
        }
        UmsMember um = umsMemberService.getUmsMemberById(member.getId());
        if (omsSettleApplyService.count(new QueryWrapper<OmsSettleApply>()
                .eq("open_id", member.getOpenId())
                .and(wrapper -> wrapper.eq("status", 0).
                        or().eq("status", 1)
                        .or().eq("status", 3))) > 0) {
            return CommonResult.failed("您有未完成的提现申请");
        }

        if (um.getBalance() < apply.getFee()) {
            return CommonResult.failed("余额不足,无法申请提现");
        }
        apply.setSettleOrderId(snowflake.nextIdStr());
        omsSettleApplyService.save(apply);
        return CommonResult.success(apply);
    }


    public static void main(String[] args) {
        Snowflake snowflake = IdUtil.getSnowflake(2, 1);
        System.out.println(snowflake.nextIdStr());
    }

    @ApiOperation("前台查询提现申请")
    @PostMapping("listSettle")
    public CommonResult<Page<OmsSettleApply>> listSettle(@RequestBody OmsSettleApply apply) {
        UmsMember member = MemberContext.getMember();
        if (member == null) {
            return CommonResult.failed("请先登录");
        }
        QueryWrapper<OmsSettleApply> query = new QueryWrapper<OmsSettleApply>().eq("open_id", member.getOpenId());
        if (apply.getStatus() != null) {
            query.eq("status", apply.getStatus());
        }
        query.orderByDesc("create_time");
        Page<OmsSettleApply> page = omsSettleApplyService.page(new Page<>(apply.getPageNum(), apply.getPageSize()),
                query);
        page.getRecords().forEach(e->e.setErrorMsg(null));
        return CommonResult.success(page);
    }

    @ApiOperation("后台审核提现申请 给id 和 status 或者是remark即可")
    @PostMapping("auditSettle")
    public CommonResult<Void> auditSettle(@RequestHeader("authorization") String authorization, @RequestBody @Validated OmsSettleApplyDTO dto) {
        String adminUsername = jwtTokenUtil.getUserNameFromToken(authorization.replace("Bearer ", ""));
        UmsAdmin admin = umsAdminService.getAdminByUsername(adminUsername);
        OmsSettleApply apply = omsSettleApplyService.getById(dto.getId());
        if (apply.getStatus() == 4 || apply.getStatus() == 2) {
            return CommonResult.failed("该申请已提现成功或者已置审核失败");

        }
        apply.setStatus(dto.getStatus());
        apply.setAssessAdminId(admin.getId());
        apply.setAssessTime(new Date());
        omsSettleApplyService.updateById(apply);

        omsSettleApplyService.handleSettleApply(apply);

        return CommonResult.success(null);
    }

    @ApiOperation("后台批量审核提现申请 给id 和 status 或者是remark即可")
    @PostMapping("batchAuditSettle")
    public CommonResult<Void> batchAuditSettle(@RequestHeader("authorization") String authorization, @RequestBody @Validated OmsSettleApplyDTO dto) {
        String adminUsername = jwtTokenUtil.getUserNameFromToken(authorization.replace("Bearer ", ""));
        UmsAdmin admin = umsAdminService.getAdminByUsername(adminUsername);
        List<OmsSettleApply> omsSettleApplies = new ArrayList<>();
        dto.getIds().forEach(id -> {
            OmsSettleApply apply = omsSettleApplyService.getById(id);
            if (apply == null) {
                return;
            }
            apply.setStatus(dto.getStatus());
            apply.setAssessAdminId(admin.getId());
            apply.setAssessTime(new Date());
            omsSettleApplies.add(apply);
        });
        omsSettleApplyService.updateBatchById(omsSettleApplies);
        for (OmsSettleApply omsSettleApply : omsSettleApplies) {
            omsSettleApplyService.handleSettleApply(omsSettleApply);
        }

        return CommonResult.success(null);
    }

    @ApiOperation("万能分页查询接口")
    @PostMapping("page")
    public CommonResult page(@RequestBody OmsSettleApply apply) {
        QueryWrapper<OmsSettleApply> queryWrapper = new QueryWrapper<>();
        if (apply.getStatus() != null) {
            queryWrapper.eq("status", apply.getStatus());
        }
        if (StringUtils.isNotEmpty(apply.getOpenId())) {
            queryWrapper.eq("open_id", apply.getOpenId());
        }
        if (apply.getAssessAdminId() != null) {
            queryWrapper.eq("assess_admin_id", apply.getAssessAdminId());
        }

        if (apply.getCreateTimeStart() != null) {
            queryWrapper.ge("create_time", apply.getCreateTimeStart());
        }
        if (apply.getCreateTimeEnd() != null) {
            queryWrapper.le("create_time", apply.getCreateTimeEnd());
        }

        if (apply.getAssessTimeStart() != null) {
            queryWrapper.ge("assess_time", apply.getAssessTimeStart());
        }
        if (apply.getAssessTimeEnd() != null) {
            queryWrapper.le("assess_time", apply.getAssessTimeEnd());
        }
        if (apply.getHandleTimeStart() != null) {
            queryWrapper.ge("handle_time", apply.getHandleTimeStart());
        }
        if (apply.getHandleTimeEnd() != null) {
            queryWrapper.le("handle_time", apply.getHandleTimeEnd());
        }

        if (StringUtils.isNotEmpty(apply.getRemark())) {
            queryWrapper.like("remark", apply.getRemark());
        }
        queryWrapper.orderByDesc("create_time");
        Page<OmsSettleApply> page = omsSettleApplyService.page(new Page<>(apply.getPageNum(), apply.getPageSize(), true), queryWrapper);
        Map<Long, String> map = umsAdminService.list().stream().collect(Collectors.toMap(UmsAdmin::getId, UmsAdmin::getUsername));
        page.getRecords().forEach(omsSettleApply -> omsSettleApply.setAssessAdminUsername(map.get(omsSettleApply.getAssessAdminId())));
        return CommonResult.success(page);
    }

    @ApiOperation("更新提现申请")
    @PostMapping("update")
    public CommonResult<Void> update(@RequestBody OmsSettleApply apply) {
        omsSettleApplyService.updateById(apply);
        return CommonResult.success(null);
    }


    @Data
    public static class OmsSettleApplyDTO {
        @ApiModelProperty("主键id 单个审核时使用")
        private Integer id;

        @ApiModelProperty("主键id  批量审核时使用")
        private List<Integer> ids;

        @ApiModelProperty("申请状态 0已申请 1 审核通过 2审核失败 3提现成功 4提现失败")
        @NotNull
        private Integer status;

        @ApiModelProperty("备注")
        private String remark;
    }
}

